package com.miao.im.scheduler;

import com.miao.im.common.CacheKey;
import com.miao.im.repository.IUserRepository;
import com.miao.im.server.session.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/5/18 10:02
 * @Description:
 */
@Component
public class WsScheduler {
    /**用于刷新在线用户*/
    private Map<String, Long> waitingRefreshUser = new ConcurrentHashMap<>();
    @Autowired
    private IUserRepository userRepository;

    /**
     * 刷新在线用户过期时间
     * @author miaoguoxin
     * @date 2021/5/18
     */
    @Scheduled(initialDelay = 10 * 1000, fixedRate = 60 * 1000)
    public void refreshOnlineUserExpireTime() {
        List<String> keys = new ArrayList<>();
        for (Map.Entry<String, Long> entry : waitingRefreshUser.entrySet()) {
            keys.add(entry.getKey());
            waitingRefreshUser.remove(entry.getKey());
        }
        userRepository.batchRefreshOnlineUser(keys);
    }

    public void addWaitingUser(String userId, String deviceNumber) {
        waitingRefreshUser.put(userId + CacheKey.SEMICOLON_DELIMITER + deviceNumber, System.currentTimeMillis());
    }

    public void removeWaitingUser(String userId, String deviceNumber){
        waitingRefreshUser.remove(userId + CacheKey.SEMICOLON_DELIMITER + deviceNumber);
    }
}
